/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-03-07     86188       the first version
 */
#include "head_rtthread.h"
#include "head_user.h"

ExFLASH_HandleTypedef ExFlash_Handle;

static void delay_ms(uint8_t ms)
{
    rt_thread_mdelay(ms);
}
//static void FM25v05_R_reg(uint8_t addr, uint8_t *res, uint32_t num)
//{
//    uint8_t dat;
//
//    dat =  addr;
//    SPI_Handle.WthenRs(SPI_Handle.SPI2dev.FM25V05, &dat, 1, res, num);
//}
static void FM25v05_W_byte(uint8_t val)
{
    SPI_Handle.RWBytes(SPI_Handle.SPI2dev.FM25V05, &val, RT_NULL, 1);
}

//static uint8_t state_register;
//static void FM25v05_RDSR(void)
//{
//    FM25v05_R_reg(RDSR, &state_register, 1);
//}
//
//static uint8_t device_ID[9];
//static void FM25v05_ID(void)
//{
//    FM25v05_R_reg(RDID, device_ID, 9);
//}

static int16_t FM25v05_reads(uint16_t addr, uint16_t num, uint8_t* buf)
{
    uint8_t dat[3];

    dat[0] =  READ;
    dat[1] =  addr>>8;
    dat[2] =  addr>>0;
    SPI_Handle.WthenRs(SPI_Handle.SPI2dev.FM25V05, dat, 3, buf, num);

    return 0;
}
static int16_t FM25v05_writes(uint16_t addr, uint16_t num, uint8_t* buf)
{
    uint8_t dat[3];

    dat[0] =  WRITE;
    dat[1] =  addr>>8;
    dat[2] =  addr>>0;

    FM25v05_W_byte(WREN);   //write enable
    SPI_Handle.WthenWs(SPI_Handle.SPI2dev.FM25V05, dat, 3, buf, num);
    FM25v05_W_byte(WRDI);   //write disable

    return 0;
}

static void FM25v05_init(void)
{
    delay_ms(10);
    //FM25v05_W_byte(WREN);   //write enable
}


static int rt_fm25v05_init(void)
{
    FM25v05_init();

    ExFlash_Handle.readData = FM25v05_reads;
    ExFlash_Handle.saveData = FM25v05_writes;

    return RT_EOK;
}
INIT_DEVICE_EXPORT(rt_fm25v05_init);
